package chapter5.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;

/**
 * Created by gzhd on 2017/11/27.
 */
public class NioCliet {
    private Selector selector;

    public void initClient(String ip, int port) throws Exception {
        SocketChannel channel = SocketChannel.open();
        channel.configureBlocking(false);
        this.selector = Selector.open();
        channel.connect(new InetSocketAddress(ip, port));
        channel.register(selector, SelectionKey.OP_CONNECT);
    }

    public void listen() throws Exception {

        while (true) {
            System.out.println("在等");
            selector.select();

            Iterator ite = this.selector.selectedKeys()
                    .iterator();
            while (ite.hasNext()) {
                SelectionKey key = (SelectionKey) ite.next();
                ite.remove();
                if (key.isConnectable()) {

                    SocketChannel channel = (SocketChannel) key.channel();
                    if (channel.isConnectionPending()) {
                        channel.finishConnect();
                    }
                    channel.configureBlocking(false);
                    channel.write(ByteBuffer.wrap("hello from cliteen".getBytes()));
                    channel.register(this.selector, SelectionKey.OP_READ);

                } else if (key.isReadable()) {
                    read(key);
                }

            }


        }
    }

    Integer i = 0;

    public  void connect(SelectionKey key)throws  Exception{
        SocketChannel channel = (SocketChannel) key.channel();
        if (channel.isConnectionPending()) {
            channel.finishConnect();
        }
        channel.configureBlocking(false);
        channel.write(ByteBuffer.wrap(new String("hello server!\r\n").getBytes()));
        channel.register(this.selector, SelectionKey.OP_READ);
    }

    private void read(SelectionKey key) throws Exception {
        SocketChannel channel = (SocketChannel) key.channel();
        ByteBuffer buffer = ByteBuffer.allocate(100);
        channel.read(buffer);
        byte[] data = buffer.array();
        String msg = new String(data).trim();
        msg += i.toString();
        System.out.println("服务端收到信息:" + msg);

//        channel.close();
//        key.selector().close();

        TimeUnit.SECONDS.sleep(1);
        ByteBuffer outbuffer = ByteBuffer.wrap(msg.getBytes());
        channel.write(outbuffer);

    }

    public static void main(String[] args) throws Exception {
//        NioClientDemo clientDemo = new NioClientDemo();
        NioCliet clientDemo = new NioCliet();
        int port = 8000;
        clientDemo.initClient("127.0.0.1", port);
        clientDemo.listen();
    }
}
